<?php
namespace App\Admin\Controllers\Operation;

use App\Admin\Actions\Operation\CalculateProfitSku;
use App\Admin\Actions\Operation\ImportProfitSku;
use App\Admin\Ajax\Operation\ProfitAjax;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysCountry;
use App\Models\Basics\ExchangeRate;
use App\Models\Basics\Transport;
use App\Models\Operation\ProfitSku;
use App\Models\Product\ProductClassify;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\DB;
class ProfitSkuController extends AdminController{

    protected $title = '公司产品利润率';

    protected function grid()
    {
        Admin::script($this->_script());
        $grid = new Grid(new ProfitSku());
        $grid->model()->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->inventory_fee = round($item->sale_price * ProfitSku::$_inventory / 100 ,3);
                $item->other_fee = round($item->sale_price * ProfitSku::$_other / 100 ,3);
                $item->commission_fee = round($item->sale_price * $item->commission / 100 ,3);
                $item->return_fee = round($item->sale_price * $item->return / 100 ,3);
                $item->vat_fee = round($item->sale_price * $item->vat / 100 ,3);
            }
            return $collection;
        });
        $grid->column('country.country','国家');
        $grid->column('seller_id','销售员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('status','异常')->using(ProfitSku::$_status)->filter(ProfitSku::$_status);
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('skuClassify.title','品类');
        $grid->column('transport','运输方式')->using(Transport::$_transport);
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称');
        $grid->column('rate_odds','汇率');
        $grid->column('tpl_rmb','TP1(RMB)');
        $grid->column('TP1')->display(function (){
            if(!$this->rate_odds){
                return '';
            }
            return numberFormat(round($this->tpl_rmb / $this->rate_odds,3));
        });
        $grid->column('head_cost','头程费')->help('平均费用or重量*运费');
        $grid->column('fba_fee','FBA费')->view('operation.profit-sku.fba-fee');
        $grid->column('inventory_fee','库存费');
        $grid->column('other_fee','其他平台费');
        $grid->column('commission','commission')->view('operation.profit-sku.commission');
        $grid->column('commission_fee','commission费');
        $grid->column('return','退货率')->display(function ($value){
            return $value.'%';
        });
        $grid->column('return_fee','退货费')->help('退货率*销售额');
        $grid->column('vat_fee','VAT费');
        $grid->column('cost','成本');
        $grid->column('sale_price','销售价格')->view('operation.profit-sku.sale-price')->help('取有FBA库存的亚马逊产品的最新订单对应的价格');
        $grid->column('profit','毛利');
        $grid->column('profit_rate','毛利率')->help('运营表取海运毛利率');
        $grid->tools(function (Grid\Tools $tools) {
            $tools->append(new ImportProfitSku());
            $tools->append(new CalculateProfitSku());
        });
        $grid->disableActions();
        $grid->fixHeader();
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('operation/profit-sku-download'));
        });
        $grid->disableRowSelector();
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/2, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/2, function ($filter) {
                $filter->in('country_id','国家')->multipleSelect(AmazonCountry::options());
                $filter->equal('seller_id','销售')->select(User::getSellerOptions());
                $filter->equal('transport','运输方式')->select(Transport::$_transport);
            });
        });
        return $grid;
    }

    protected function __options($name){
        $options = json_encode([
            'emptytext'  => '<i class="fa fa-pencil"></i>',
            'mode' => 'inline',
            "showbuttons" => false,
            'name' => $name,
        ]);

        return substr($options, 0, -1).<<<'STR'
    ,
    "success":function(response, newValue){
        if (typeof response === 'object') {
            $.pjax.reload('#pjax-container');
            if (response.status){
                $.admin.toastr.success(response.message, '', {positionClass:"toast-top-center"});
            } else {
                $.admin.toastr.error(response.message, '', {positionClass:"toast-top-center"});
            }
        }
    }
}
STR;
    }

    protected function _script()
    {
        $options1 = $this->__options('fba_fee');
        $options2 = $this->__options('sale_price');
        $options3 = $this->__options('commission');

        return <<<EOT
$('.grid-editable-fba_fee').editable($options1);
$('.grid-editable-sale_price').editable($options2);
$('.grid-editable-commission').editable($options3);
EOT;
    }

    public function update($id)
    {
        try{
            $name = Request::get('name');
            $value = trim(Request::get('value'));
            DB::beginTransaction();
            $model = ProfitSku::query()->find($id);
            $model->{$name} = $value;
            $flag = $model->save();
            if(!$flag){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }
            $currencyCode = AmazonCountry::query()->where('country_id',$model->country_id)->value('currency_code');
            if($currencyCode){
                $model->rate_odds = ExchangeRate::getRateOddsToRMB($currencyCode,time());
            }
            $tpl = round($model->tpl_rmb / $model->rate_odds,3);
            $model->cost = ProfitSku::getCost($tpl,$model->sale_price,$model->head_cost,$model->fba_fee,$model->commission,$model->return,$model->vat);
            $model->profit = round($model->sale_price - $model->cost,3);
            $model->profit_rate = $model->sale_price == 0 ? 0 : round($model->profit / $model->sale_price,3);
            $fbaFeeFlag = $model->country_id == 20 ? false : true;
            $model->status = ProfitSku::getStatus($model->status,$model->sale_price,$model->fba_fee,$fbaFeeFlag,$model->commission);
            $flag1 = $model->save();
            if(!$flag1){
                DB::rollBack();
                return response()->json(['status' => false, 'message' => '操作失败！']);
            }else{
                DB::commit();
                return response()->json(['status' => true, 'message' => '操作成功！']);
            }
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
            return response()->json(['status' => false, 'message' => '系统错误！']);
        }
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new ProfitAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ProfitSku::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if($key == 'status'){
                $query->whereIn('status', $_filter);
            }
            if($key == 'country_id'){
                $query->whereIn('country_id', $_filter);
            }
            if(in_array($key,['seller_id','transport'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['国家','销售员','季节性','品类','运输方式', 'SKU','产品名称',
            '汇率','TP1(RMB)','TP1','头程费','FBA费','库存费','其他平台费','commission',
            'commission费','退货率','退货费','VAT费','成本','销售价格','毛利','毛利率'];
        RExcel::exportCsv('公司产品利润率',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    public static function getDownloadData($res)
    {
        $country = [];
        $seller = [];
        foreach ($res as $model){
            if(!array_key_exists($model->country_id,$country)){
                $country[$model->country_id] = SysCountry::getCountryById($model->country_id);
            }
            if(!array_key_exists($model->seller_id,$seller)){
                $seller[$model->seller_id] = User::getUsernameById($model->seller_id);
            }
            $temp = [
                $country[$model->country_id],
                $seller[$model->seller_id],
                ProductClassify::$_season[$model->skuClassify->season ?? 3],
                $model->skuClassify->title ?? '',
                Transport::$_transport[$model->transport],
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                $model->rate_odds,
                $model->tpl_rmb,
                !$model->rate_odds ? '' : numberFormat(round($model->tpl_rmb / $model->rate_odds,3)),
                $model->head_cost,
                $model->fba_fee,
                round($model->sale_price * ProfitSku::$_inventory / 100 ,3),
                round($model->sale_price * ProfitSku::$_other / 100 ,3),
                $model->commission.'%',
                round($model->sale_price * $model->commission / 100 ,3),
                $model->return.'%',
                round($model->sale_price * $model->return / 100 ,3),
                round($model->sale_price * $model->vat / 100 ,3),
                $model->cost,
                $model->sale_price,
                $model->profit,
                $model->profit_rate,
            ];
            yield $temp;
        }
    }
}
